<template>
  <sec-select
    v-model="selectItemArr"
    multiple
    collapse-tags
    placeholder="所属组织"
    clearable
    popper-class="select-multiple"
    @visible-change="initData"
    @clear="removeTag"
  >
    <div class="select-box">
      <sec-input
        v-model="searchValue"
        size="medium"
        class="select-search"
        placeholder="请输入搜索内容"
        suffix-icon="sec-icon-sousuo"
        clearable
        @input="searchCat"
      >
      </sec-input>

      <div v-if="companyOpt.length" class="select-content">
        <div
          v-for="(item, index) in companyOpt"
          :key="item.value"
          class="select-item"
        >
          <div class="select-parent" @click="changExpand(index)">
            <div>
              <sec-checkbox
                v-model="item.checked"
                :indeterminate="item.isIndeterminate"
                @change="(e) => selectAllCategory(e, index)"
              ></sec-checkbox>
              <span class="select-parent__label">{{ item.label }}</span>
            </div>
            <i v-if="item.expand" class="el-icon-caret-bottom"></i>
            <i v-else class="el-icon-caret-right"></i>
          </div>
          <div
            v-show="item.expand && item.children && item.children.length"
            class="select-children"
          >
            <sec-option
              v-for="(subItem, idx) in item.children"
              :key="idx"
              :value="subItem.value"
              :label="subItem.label"
              @click.native="checkAllContrl(subItem, index)"
            >
              <span class="check"></span>
              <span class="check-label">{{ subItem.label }}</span>
            </sec-option>
          </div>
        </div>
      </div>
      <div v-else class="select-content empty">
        <sec-option disabled value="暂无数据" label="暂无数据"></sec-option>
      </div>
    </div>
  </sec-select>
</template>
<script>
import { arrayToTree } from '@/utils/util'
import http from '@/utils/http'
export default {
  data() {
    return {
      searchValue: '',
      selectItemArr: [],
      companyOpt: [],
      originList: [],
      loading: false
    }
  },
  watch: {
    selectItemArr() {
      this.dataChange()
    }
  },
  mounted() {
    this.getCatMod()
  },
  methods: {
    /**
     * @description: 当下拉框显示的时候请求接口
     * @param {Boolean} val
     * @return {*}
     */
    initData(val) {
      if (!val) {
        this.searchValue = ''
      }
    },
    /**
     * @description: 获取组织架构接口
     * @return {*}
     */
    async getCatMod() {
      try {
        const { data } = await http.ddsgListByLoginInfo()
        const result = data.map((item) => ({
          ...item,
          pid: item.parentId,
          label: item.name,
          value: item.id
        }))
        this.originList = result
        this.companyOpt = this.richResult(result)
      } catch (error) {
        console.log(error)
      }
    },
    /**
     * @description: 展开状态切换
     * @param {Number} index 树根节点下标
     * @return {*}
     */
    changExpand(index) {
      this.companyOpt[index].expand = !this.companyOpt[index].expand
    },
    dataChange() {
      this.$emit('change', this.selectItemArr)
    },
    removeTag() {
      this.selectItemArr = []
      this.companyOpt = this.richResult(this.originList)
    },
    /**
     * @description: 单个类别全选
     * @param {Boolean} val 全选状态
     * @param {Number} index 树根节点下标
     * @return {*}
     */
    selectAllCategory(val, index) {
      this.companyOpt[index].checkedArr = val
        ? this.companyOpt[index].children.map((item) => item.value)
        : []
      const selectItemArr = []
      this.companyOpt.forEach((item) => {
        if (item.checkedArr.length) {
          item.checkedArr.forEach((subitem) => {
            selectItemArr.push(subitem)
          })
        }
      })
      this.selectItemArr = Array.from(new Set(selectItemArr))
      this.companyOpt[index].isIndeterminate = false
      this.companyOpt[index].expand = this.selectItemArr.length > 0
    },
    /**
     * @description: 单个公司选择
     * @param {String} val 选中值
     * @param {Number} index 树根节点下表
     * @return {*}
     */
    checkAllContrl(subItem, index) {
      if (this.companyOpt[index].checkedArr.includes(subItem.value)) {
        this.companyOpt[index].checkedArr = this.companyOpt[
          index
        ].checkedArr.filter((item) => item !== subItem.value)
        console.log(this.companyOpt[index].checkedArr, '.....')
      } else {
        this.companyOpt[index].checkedArr.push(subItem.value)
      }
      this.checkStatus(index)
    },
    /**
     * @description: 复选框状态、展开状态校验
     * @param {Number} index 下标
     * @return {*}
     */
    checkStatus(index) {
      if (
        this.companyOpt[index].checkedArr.length ===
        this.companyOpt[index].children.length
      ) {
        this.companyOpt[index].checked = true
        this.companyOpt[index].isIndeterminate = false
      } else if (this.companyOpt[index].checkedArr.length) {
        this.companyOpt[index].isIndeterminate = true
        this.companyOpt[index].expand = true
        this.companyOpt[index].checked = false
      } else {
        this.companyOpt[index].isIndeterminate = false
        this.companyOpt[index].checked = false
      }
    },
    /**
     * @description: 模糊搜索子类不支持父类
     * @param {String} val
     * @return {*}
     */
    searchCat(val) {
      if (!val) {
        this.companyOpt = this.richResult(this.originList)
        return
      }
      const parentList = []
      const filterList = this.originList.filter(
        (item) => item.label.includes(val) && item.pid !== '0'
      )
      filterList.forEach((item) => {
        this.originList.forEach((el) => {
          if (el.id === item.pid) {
            parentList.push(el)
          }
        })
      })
      const result = [...filterList, ...new Set(parentList)]
      this.companyOpt = this.richResult(result)
    },
    // 丰富接口返回值
    /**
     * @description: 丰富接口返回值
     * @param {Array} result 接口返回原数据
     * @return {Array}
     */
    richResult(result) {
      const treeData = arrayToTree(result)
      const res = treeData.map((item) => ({
        ...item,
        children: (item.children || []).map((item) => ({
          label: item.name,
          value: item.id
        })),
        checkedArr: [],
        checked: false,
        isIndeterminate: false,
        expand: false
      }))
      this.selectItemArr.forEach((item) => {
        res.forEach((el) => {
          if (el.children.findIndex((a) => a.value === item) >= 0) {
            el.checkedArr.push(item.value)
          }
          if (el.children.length === el.checkedArr.length) {
            el.checked = true
            el.isIndeterminate = false
          } else if (el.checkedArr.length) {
            el.checked = false
            el.expand = true
            el.isIndeterminate = true
          } else {
            el.checked = false
            el.isIndeterminate = false
          }
        })
      })
      return res
    }
  }
}
</script>
<style lang="scss">
.select-multiple {
  .select-box {
    min-height: 284px;
    width: 512px;
    .select-search {
      width: 480px;
      margin: 0px 16px 8px;
    }
    .select-item {
      .select-parent {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 16px;
        box-sizing: border-box;
        height: 36px;
        background: #f5f5f5;
        &__label {
          margin-left: 8px;
          font-size: 12px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #262626;
          line-height: 18px;
        }
      }
    }
    .select-content {
      &.empty {
        text-align: center;
      }
    }
    .select-children {
      padding-left: 24px;
      .check-label {
        margin-left: 8px;
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #262626;
        line-height: 18px;
      }
      .el-select-dropdown__item.selected {
        background: transparent;
      }
    }

    .el-select-dropdown__item {
      padding: 0;
      display: inline-block;
      width: 80px;
      box-sizing: border-box;
      &.hover {
        background: transparent;
      }
    }
    .el-select-dropdown__item.selected::after {
      content: '';
    }
    .el-select-dropdown__item.selected .check {
      background-color: #3366ff;
      border-color: #3366ff;
    }
    .el-select-dropdown__item.selected .check:after {
      transform: rotate(45deg) scaleY(1);
    }
    .el-select-dropdown__item .check::after {
      box-sizing: content-box;
      content: '';
      border: 1px solid #fff;
      border-left: 0;
      border-top: 0;
      height: 7px;
      left: 5px;
      position: absolute;
      top: 1px;
      transform: rotate(45deg) scaleY(0);
      width: 3px;
      transition: transform 0.15s ease-in 0.05s;
      transform-origin: center;
    }
    .el-select-dropdown__item .check {
      display: inline-block;
      position: relative;
      top: 3px;
      border: 1px solid #d9d9d9;
      border-radius: 2px;
      box-sizing: border-box;
      width: 16px;
      height: 16px;
      background-color: #fff;
      z-index: 1;
      transition: border-color 0.25s cubic-bezier(0.71, -0.46, 0.29, 1.46),
        background-color 0.25s cubic-bezier(0.71, -0.46, 0.29, 1.46);
    }
  }
  .el-select-dropdown__wrap {
    max-height: 300px !important;
  }
}
</style>
